package main

import ( 
    "fmt"
    "image"
    png "image/png"
    jpg "image/jpeg"
    "log"
    "os"
    "io"
    "io/ioutil"
    "github.com/BurntSushi/graphics-go/graphics"
    "strconv"
    "time"
    "flag"
    "path/filepath"
    "strings"
)

var (
    h bool
    src string
    dst string
    width int 
//    ch chan string = make(chan string, 30)
)

func main() {
    // 设置初始参数 
    fmt.Println("dst_width: ", width)
    fmt.Println("请稍等: ...")
    // 自动创建目标文件夹
    os.Mkdir(dst, os.ModePerm)

    // 命令帮助文档
    if h {
        flag.Usage() 
    } 
    // fmt.Println(src, dst, width)

    // 遍历获取文件列表
//    files := getFilelist(src)
    files := listAll(src)
    for i := range files{
        names := strings.Split(files[i], ".")
        name := names[0]
        postfix := names[1]
        // fmt.Println(name, postfix)

        srcFile := fmt.Sprintf("%s/%s", src, files[i])
        dstFile := fmt.Sprintf("%s/%s_%d.%s", dst, name, width, postfix)
        go convert(srcFile, width, dstFile, postfix)
    }
    time.Sleep(2 * time.Second)

    dd()

    
//    for i:=2; i <= 100; i++ {
//        dstFile = fmt.Sprintf("imgs/%d.png", i)
//        go convert(img, width, dstFile)
//        // convert(img, dstWidth, dstFile)
//    }
    time.Sleep(2 * time.Second)
}

func getFilelist(path string) []string {
//    go func() {
    var files []string
    
        err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
            if (f == nil) {return err}
            if f.IsDir() {return nil}
            files = append(files, path)
            return nil
        })
//   }()

    return files
}

func listAll(path string) []string {
    var tmp_files []string

    files, _ := ioutil.ReadDir(path)
    for _, fi := range files {
        if fi.IsDir() {
            println(path + "/" + fi.Name())
        } else {
            tmp_files = append(tmp_files, fi.Name())
        }
    }

    return tmp_files
}

func dd() {
    os.Exit(0)
}

func init() {
    // 定义参数
    parse()
    //改变默认的Usage
    flag.Usage = usage
    // 解析参数
    flag.Parse()
}

func usage() {
    fmt.Fprintf(os.Stderr, `图片缩放小工具
Options:
`)
    flag.PrintDefaults()
}

func parse() {
    dst_path := ""
    flag.BoolVar(&h, "h", false, "this help")
    flag.StringVar(&src, "src", "./src", "source image path")
    flag.StringVar(&dst, "dst", "./dst", "dest image path")
    flag.IntVar(&width, "width", 240, "width of resize")
}

func convert(img string, dstWidth int, dstFile string, postfix string){

    c, _, err := image.DecodeConfig(OpenFile(img))
    // fmt.Println(c.Width, c.Height, postfix)

    src, err := LoadImage(img)
    if err != nil {
        log.Fatal(err)
    }
    bound := src.Bounds()
    dx := bound.Dx()
    dy := bound.Dy()
    newdx := dstWidth 

    // 缩略图的大小
    dst := image.NewRGBA(image.Rect(0, 0, newdx, newdx*dy/dx))
    // 产生缩略图，等比例缩放
    err = graphics.Scale(dst, src)
    check(err)

    // save
    file1, err := os.Create(dstFile)
    check(err)
    defer file1.Close()

    switch postfix {
        case "jpg":
            jpg.Encode(file1, dst, nil)
        case "png": 
            png.Encode(file1, dst)
    } 
}

func check(e error) {
    if e != nil {
        log.Fatal(e)
        panic(e)
    }
}

func OpenFile(path string) (file io.Reader) {
    file, err := os.Open(path)
    if err != nil {
        return
    }
    // defer file.Close()

    return 
}

func LoadImage(path string) (img image.Image, err error) {
    file, err := os.Open(path)
    if err != nil {
        return
    }
    defer file.Close()

    img, _, err = image.Decode(file)
    return
}
